/*

This file is part of roomyak.

Copyright (C) 2008 Pixecur Technologies Incorporated (Esotera).
Visit Esotera at http://www.esoteras3.com
 
roomyak is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3, or (at your option)
any later version.
 
roomyak is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.
 
You should have received a copy of the GNU General Public License
along with roomyak; see the file COPYING.  If not, write to 
Pixecur Technologies, 213-31 Peet Street, St. John's, NL, A1B 3W8. 
 
Linking this library statically or dynamically with other modules is
making a combined work based on this library.  Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
 
*/
package com.datasentinel.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;


public class FileHelper
{
	private static final Logger logger =  Logger.getLogger(FileHelper.class.getName());
	
	public static boolean shrinkFile(File file, long expectedLength)
	{
		if(file == null || !file.exists() || !file.isFile() || file.length() < expectedLength)
		{
			logger.warning("Trying to decrease the size of the invalid file.");
			return false;
		}
		BufferedInputStream is = null;
		BufferedOutputStream os = null;
		File tempFile = null;
		try{
			tempFile = File.createTempFile(file.getName(), ".~px_tmp", file.getParentFile());
			
			is = new BufferedInputStream(new FileInputStream(file));
			os = new BufferedOutputStream(new FileOutputStream(tempFile));
			
			byte[] block = new byte[1024];
			
			long totalReadByteCount = 0;
			int readByteCount = 0;
			while(totalReadByteCount < expectedLength &&(readByteCount = is.read(block)) >= 0)
			{
				if((totalReadByteCount + readByteCount) <= expectedLength)
					totalReadByteCount += readByteCount;
				else
				{
					readByteCount = (int)(expectedLength - totalReadByteCount);
					totalReadByteCount += readByteCount;
				}
					
				if(readByteCount > 0)
					os.write(block, 0, readByteCount);
			}
			
			os.close();
			is.close();

			if(!file.delete())
			{
				logger.warning("Failed to delete the original file.");
				return false;
			}
			
			if(!tempFile.renameTo(file))
			{
				logger.warning("Failed to move the shrinked file.");
				return false;
			}
		}
		catch(IOException e)
		{
			logger.log(Level.WARNING, "Unable to decrease the size of the file.", e);
			tempFile.delete();
		}
		
		return true;
	}
}
